package zcw.com.lib_leet_code;

/**
 * Created by 朱城委 on 2021-7-9.<br><br>
 *
 * 求众数
 */
public class Topic169 {
    public static void main(String[] args) {
        Topic169 instance = new Topic169();

        int[] array = new int[] {3,2,3};
        System.out.println(instance.majorityElement(array));

        array = new int[] {2,2,1,1,1,2,2};
        System.out.println(instance.majorityElement(array));
    }

    public int majorityElement(int[] nums) {
        int counter = 0;
        int result = nums[0];

        for(int value : nums) {
            if(counter == 0) {
                result = value;
                counter++;
            }
            else if(value == result) {
                counter++;
            }
            else {
                counter--;
            }
        }

        return result;
    }
}
